Previous Book Contents Book Index Next

Inside Macintosh: AppleScript Language Guide / Part 2 - AppleScript Language Reference
Chapter 8 - Handlers / Using Subroutines


Recursive Subroutines

A recursive subroutine is a subroutine that calls itself. Recursive subroutines are legal in AppleScript. You can use them to perform repetitive actions. For example, this recursive subroutine generates a factorial.

on factorial(x)
   if x > 0 then
      return x * (factorial(x - 1))
   else
      return 1
   end if
end factorial

factorial(10)
To generate 10 factorial, the subroutine factorial is called once from the
top level of the script, and then calls itself ten more times, until the value of
x is 0. When x is equal to 0, AppleScript skips to the Else clause and finishes executing all the partially executed subroutines, including the original factorial subroutine call.

When you call a recursive subroutine, AppleScript keeps track of the variables and pending statements in the original (partially executed) subroutine until the recursive subroutine has completed. The limit on the number of pending subroutines depends on the amount of memory available.


Previous Book Contents Book Index Next

© Apple Computer, Inc.
13 JUL 1996